package br.com.felix.fwt.ui;

import java.io.PrintWriter;

import org.apache.log4j.Logger;

import br.com.felix.fwt.log.LoggerFactory;
import br.com.felix.fwt.ui.css.Position;
import br.com.felix.fwt.ui.css.Style;
import br.com.felix.fwt.ui.exception.ComponentRenderException;
import br.com.felix.fwt.ui.javascript.Javascript;

/**
 * Class used to display content as a "floating window, a dialog".
 * */
public class Dialog extends Panel{

    private static final long serialVersionUID = 5548195399214054298L;
    
    private static Javascript jsFindPos;

    private static Logger logger = LoggerFactory.getLogger(Dialog.class);

    /**
     * Instantiates a new Dialog.
     * @param relativeComponent is the component which the dialog will render near to.
     * */
    public Dialog(Form parent, final BaseComponent relativeComponent){
        Javascript js = new Javascript(){
            @Override
            public String script() {
                StringBuilder strb = new StringBuilder();
                String me = Dialog.this.getName();
                String other = relativeComponent.getName();
                strb.append("var me; \n var other; \n ; var position; \n")
                    .append("me = document.getElementById('").append(me).append("');\n")
                    .append("other = document.getElementById('").append(other).append("'); \n")
                    .append("position = findPos(other); \n")
                    .append("me.style.top=position[0]+'px';\n")
                    .append("me.style.left=position[1]+'px';\n");
                return strb.toString();
            }
        };
        if(jsFindPos==null){
            initializeJsFindPosition();
        }
        parent.executeJavascriptOfComponent(this, jsFindPos, js);
    }

    private void initializeJsFindPosition() {
        StringBuilder strb = new StringBuilder();
        strb.append("function findPos(obj){\n");
        strb.append("var top; \n var left;\n top = obj.offsetTop; \n left = obj.offsetLeft + obj.offsetWidth; \n obj = obj.offsetParent; \n");
        strb.append("while(obj!=null){\n");
        strb.append(" top += obj.offsetTop; \n left += obj.offsetLeft; \n obj = obj.offsetParent; \n } ");
        strb.append(" return [top, left]; \n }");
        final String script = strb.toString();
        jsFindPos = new Javascript() {
            @Override
            public String script() {
                return script;
            }
        };
    }

    
    
    @Override
    public void setStyle(Style style) {
        super.setStyle(style.position(Position.FIXED));
    }

    
    @Override
    public void write(PrintWriter out) throws ComponentRenderException {
        if(style==null){
            logger.warn("Dialog without style.");
        }
        super.write(out);
    }
    
    
    
}
